package org.y3soft.com.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.y3soft.com.domin.FileStore;
import org.y3soft.com.service.IFileManager;

import java.io.*;
import java.util.Base64;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Created by ydy on 2017/2/27.
 */
public class IFileManagerImpl implements IFileManager {
    private String rootPath;
    private final static AtomicLong atom = new AtomicLong(System.currentTimeMillis());
    private final static String DELITER = "-";
    private static Logger TRACE = LoggerFactory.getLogger(IFileManagerImpl.class);

    public IFileManagerImpl(String rootPath){
        this.rootPath = rootPath;
    }

    @Override
    public FileStore saveFile(String fileName,InputStream inputStream) {
        StringBuilder pathBase64 = new StringBuilder(30);
        StringBuilder fileNameBase64 = new StringBuilder(30);

        //路径的base64编码
        pathBase64.append(
                Base64.getEncoder().withoutPadding().encodeToString(this.rootPath.getBytes()))
                .append(DELITER);
                //文件的唯一编码
        fileNameBase64.append(String.valueOf(atom.getAndDecrement())).append(DELITER)
                //文件名
                .append(Base64.getEncoder().withoutPadding().encodeToString(fileName.getBytes()));

        File file = new File(this.rootPath+"/"+fileNameBase64.toString());
        if(file.exists()){
            return null;
        }
        OutputStream os = null;
        try {
            os = new FileOutputStream(file);
            byte[] bytes = new byte[1024];
            while (inputStream.read(bytes) != -1){
                os.write(bytes);
            }
            os.flush();
        } catch (FileNotFoundException e) {
            TRACE.error("保存文件错误，文件未找到",e);
            return null;
        } catch (IOException e) {
            TRACE.error("保存文件错误，保存文件时出错",e);
        } finally {
            if(os != null)
                try {
                    os.close();
                } catch (IOException e) {
                }
        }

        return new FileStore(fileName,pathBase64.append(fileNameBase64.toString()).toString());
    }

    @Override
    public String getFileName(String fileCode) {
        String encodedFileName = fileCode.substring(fileCode.lastIndexOf(DELITER)+1);
        byte[] base64 = Base64.getDecoder().decode(encodedFileName);
        return new String(base64);
    }

    @Override
    public String getFilePath(String fileCode) {
        String encodedFilePath = fileCode.substring(0,fileCode.indexOf(DELITER));
        return new String(Base64.getDecoder().decode(encodedFilePath));
    }

}
